package asia.kalin.service.impl;

import asia.kalin.domain.ao.Result;
import asia.kalin.domain.po.PriceAssess;
import asia.kalin.domain.vo.PriceAssessVO;
import asia.kalin.enums.RedisKeyEnums;
import asia.kalin.mapper.PriceAssessMapper;
import asia.kalin.service.IPriceAssessService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kalin
 * @since 2025-03-10
 */
@Service
@RequiredArgsConstructor
public class PriceAssessServiceImpl extends ServiceImpl<PriceAssessMapper, PriceAssess> implements IPriceAssessService {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 根据检测结果id查询解决方案评估价格
     * @param resultId 检测结果id
     * @return Result
     */
    @Override
    public Result getPriceAssessById(String resultId) {
        // 拼接key
        String key = RedisKeyEnums.PRICE_ASSESS_INFO_KEY + resultId;
        // 查询redis
        String object = stringRedisTemplate.opsForValue().get(key);
        // 不为空
        if(StrUtil.isNotBlank(object)){
            PriceAssessVO priceAssessVO = JSONUtil.toBean(object, PriceAssessVO.class);
            return new Result<>(0,"查询成功",priceAssessVO);
        }

        // 为空 查询数据
        PriceAssess priceAssess = baseMapper.selectOne(new QueryWrapper<PriceAssess>()
                .eq("result_id",resultId)
        );
        if(priceAssess == null){
            return new Result<>(1,"ID错误",null);
        }

        // 转换类型
        PriceAssessVO priceAssessVO = BeanUtil.toBean(priceAssess, PriceAssessVO.class);
        // 转换成json
        String jsonStr = JSONUtil.toJsonStr(priceAssessVO);
        // 写入redis
        stringRedisTemplate.opsForValue().set(key,jsonStr,RedisKeyEnums.PRICE_ASSESS_INFO_TTL, TimeUnit.HOURS);

        return new Result<>(0,"查询成功",priceAssessVO);
    }
}
